import os
import time

from PIL import Image

import move_heic_by_year


def move_photos(source_dir):
    for root, dirs, files in os.walk(source_dir):
        for file in files:
            file_path = os.path.join(root, file)
            try:
                if file.endswith(('.JPG', '.jpg')):  # 假设的 EHIC 文件扩展名
                    # 获取图片信息
                    with Image.open(file_path) as img:
                        exif_data = img._getexif()
                    if exif_data:
                        # 获取拍摄时间
                        date_taken = exif_data.get(36867)
                        if date_taken:
                            year = time.strftime("%Y", time.strptime(
                                date_taken[:19], "%Y:%m:%d %H:%M:%S"))
                            # 创建对应年份的文件夹
                            target_dir = os.path.join(source_dir, f"{year}年")
                            if not os.path.exists(target_dir):
                                os.makedirs(target_dir)
                            # 移动照片
                            os.rename(file_path, os.path.join(target_dir, file))
            except Exception as e:
                print(f"处理 {file_path} 时出错: {e}")


# 指定目录
source_dir = "F:\\糖宝照片\\2019年"
move_photos(source_dir)
# move_heic_by_year.move_photos(source_dir)
